
package com.x52im.mall.logic.score;

import java.util.ArrayList;
import java.util.Vector;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.eva.android.widget.DataLoadingAsyncTask;
import com.eva.framework.dto.DataFromClient;
import com.eva.framework.dto.DataFromServer;
import com.eva.framework.dto.SysActionConst;
import com.x52im.mall.HttpServiceFactory4AImpl;
import com.x52im.mall.PayPalConfig;
import com.x52im.mall.dto.CommonProcessorConst;
import com.x52im.mall.score.dto.JobDispatchConst;
import com.x52im.mall.score.dto.TokenRechangeHistory;
import com.x52im.rbchat.R;
import com.x52im.mall.MallGlobal;
import com.x52im.mall.Utility;
import com.x52im.mall.logic.shop.HistoryListAdapter;
import com.eva.android.widget.DataLoadableActivity;
import com.eva.android.widget.WidgetUtils;
import com.eva.android.widget.WidgetUtils.ToastType;
import com.eva.epc.common.util.CommonUtils;
import com.paypal.android.sdk.payments.PayPalService;

public class RechargeActivity extends DataLoadableActivity
{
	private Button buyBtn;
	private EditText scoreCount;
	private TextView payAmount;
	/** 文本标签：当前积份 */
	private TextView viewCurrentTokenCount = null;
	/** 按钮：充值历史 */
	private Button btnGoToChongZhiHistory = null;
	/** 没有历史记录时显示的ui提示 */
	private ViewGroup layoutForNoDataHint = null;
	
	private HistoryListAdapter lvRechangeHistoryAdapter;
	private ListView rechangeHistoryListView;
	
	/** 按钮：刷新 */
	private Button btnRefresh = null;

	// 货币类型美元
	public static final String CURRENCY_DOLLAR = "0";

	// PayPal支付方式
	public static final String PAY_TYPE_PAYPAL = "0";
	
	// set to PaymentActivity.ENVIRONMENT_LIVE to move real money.
	// set to PaymentActivity.ENVIRONMENT_SANDBOX to use your test credentials from https://developer.paypal.com
	// set to PaymentActivity.ENVIRONMENT_NO_NETWORK to kick the tires without communicating to PayPal's servers.

	@Override
	protected void initViews(Bundle savedInstanceState)
	{
		customeTitleBarResId = R.id.common_score_layout_rechange_titleBar;
		
		// 首先设置contentview
		setContentView(R.layout.common_score_layout_recharge_activity);
		// 设置标题
		this.setTitle(R.string.common_mall_recharge_title);
		// 各组件初始化
		buyBtn = (Button) this.findViewById(R.id.recharge_buy_btn);
		scoreCount = (EditText) this.findViewById(R.id.recharge_score_count_text);
		payAmount = (TextView) this.findViewById(R.id.recharge_score_pay_amount);
		viewCurrentTokenCount = (TextView) findViewById(R.id.common_mall_main_layout_entrance_score_scoreAmountView);
		btnGoToChongZhiHistory = (Button) findViewById(R.id.common_mall_main_layout_entrance_score_goToChongZhiHistoryBtn);
		btnRefresh = (Button) findViewById(R.id.common_mall_main_layout_entrance_jifen_refreshBtn);
		layoutForNoDataHint = (ViewGroup) findViewById(R.id.rechange_history_list_view_notDataHintLL);
		
		rechangeHistoryListView = (ListView) this.findViewById(R.id.rechange_history_list_view);
		lvRechangeHistoryAdapter = new HistoryListAdapter(this){
			@Override
			public void notifyDataSetChanged()
			{
				super.notifyDataSetChanged();
				//
				if(listData != null && listData.size() > 0)
					layoutForNoDataHint.setVisibility(View.GONE);
				else
					layoutForNoDataHint.setVisibility(View.VISIBLE);
			}
		};
		rechangeHistoryListView.setAdapter(lvRechangeHistoryAdapter);
		
		startService(PayPalConfig.getPayPalServiceIntent(RechargeActivity.this));
		
		// 当用户没用登陆时作未登陆的处理
		if(!MallGlobal.getMallProviderInstance(RechargeActivity.this).getRobotimeMall().isUserLogin())
			MallGlobal.getMallProviderInstance(RechargeActivity.this).getRobotimeMall().processForUserUnLogin(RechargeActivity.this);
		else
		{
			refreshCurrentTokenCountAsync();
		}
	}

	@Override
	protected void initListeners()
	{
		buyBtn.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				if (Utility.isEmpty(scoreCount.getText().toString()))
				{
					Toast.makeText(RechargeActivity.this, R.string.common_mall_recharge_score_count_tip, Toast.LENGTH_LONG).show();
				}
				else
				{
					androidx.appcompat.app.AlertDialog al = new androidx.appcompat.app.AlertDialog.Builder(RechargeActivity.this)
							.setTitle(RechargeActivity.this.getString(R.string.general_prompt))
							.setMessage("本APP仅作演示和技术体验之用，为防止被非法利用，此功能已关闭！")
							.setPositiveButton(RechargeActivity.this.getString(R.string.general_got_it), null)
							.show();

//					TokenRechangeHistory rechange = new TokenRechangeHistory();
//					rechange.setUser_uid(MallGlobal.getMallProviderInstance(RechargeActivity.this).getRobotimeMall().getLoginedUserUid());
//					rechange.setHistory_currency(RechargeActivity.CURRENCY_DOLLAR);
//					rechange.setPay_type(RechargeActivity.PAY_TYPE_PAYPAL);
//					rechange.setHistory_amount(String.valueOf(payAmount.getText()).trim());
//					rechange.setHistory_token(String.valueOf(scoreCount.getText()).trim());
//
//					startActivityForResult(IntentFactory.createPaymentActivityIntent(RechargeActivity.this, null, rechange, CommonPaymentActivity.PAYPAL_PAYMENT_INTEGRAL) , 0);
				}
			}
		});
		
		btnGoToChongZhiHistory.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				// 当用户没用登陆时作未登陆的处理
				if(!MallGlobal.getMallProviderInstance(RechargeActivity.this).getRobotimeMall().isUserLogin())
					MallGlobal.getMallProviderInstance(RechargeActivity.this).getRobotimeMall().processForUserUnLogin(RechargeActivity.this);
				else
				{
					Intent intent = new Intent(RechargeActivity.this, RechargeHistoryActivity.class);
					startActivity(intent);
				}
			}
		});
		
		btnRefresh.setOnClickListener(new OnClickListener()
		{
			@Override
			public void onClick(View v)
			{
				// 当用户没用登陆时作未登陆的处理
				if(!MallGlobal.getMallProviderInstance(RechargeActivity.this).getRobotimeMall().isUserLogin())
					MallGlobal.getMallProviderInstance(RechargeActivity.this).getRobotimeMall().processForUserUnLogin(RechargeActivity.this);
				else
				{
					refreshCurrentTokenCountAsync();
				}
			}
		});
		
		
		scoreCount.addTextChangedListener(new TextWatcher()
		{

			@Override
			public void onTextChanged(CharSequence s, int start, int before, int count)
			{
				String countText = scoreCount.getText().toString();
				if (!Utility.isEmpty(countText))
					payAmount.setText(String.valueOf(CommonUtils.getScaledValue(CommonUtils.getDoubleValue(countText) * TokenRechangeHistory.SCORE_DOLLAR_SCALE, 2,
							false)));
				else
					payAmount.setText("");
			}

			@Override
			public void beforeTextChanged(CharSequence s, int start, int count, int after)
			{
				// TODO Auto-generated method stub
			}

			@Override
			public void afterTextChanged(Editable s)
			{
				// TODO Auto-generated method stub

			}
		});
	}
	
	//定义Handler对象
	private Handler handler = new Handler()
	{
		@Override
		// 当有消息发送出来的时候就执行Handler的这个方法
		public void handleMessage(Message msg)
		{
			super.handleMessage(msg);
			// 处理UI
		}
	};

	
	public void refreshCurrentTokenCountAsync()
	{
		// 异步刷新当前用户的最新积分
		new RefreshCurrentTokenCountAsync(RechargeActivity.this).execute();
	}
	
	/**
	 * 异步刷该用户当前的积分数.
	 * 
	 * @author Jack Jiang, 2013-09-26
	 * @version 1.0
	 */
	public class RefreshCurrentTokenCountAsync extends DataLoadingAsyncTask<String, Integer, DataFromServer>
	{
		public RefreshCurrentTokenCountAsync(Context context)
		{
			super(context);
		}

		/**
		 * 参数0就是当前用户的UID。
		 */
		@Override
		protected DataFromServer doInBackground(String... params)
		{
			MallGlobal rm = MallGlobal.getMallProviderInstance(context).getRobotimeMall();
			if(!rm.isUserLogin())
				return Utility.constructFalseDFS();
			else
				return HttpServiceFactory4AImpl.AToolKits.queryDataRoot(rm.getAuthedService()
						, "select current_token_count from token_user_token where user_uid = '"+rm.getLoginedUserUid()+"'");
//			return AToolKits.queryDataRoot(_Utils.getService()
//					, "select current_token_count from token_user_token where user_uid = '"+_Utils.getLoginedUserUid()+"'");
		}

//		protected void onPostExecute(DataFromServer dfs)
//		{
//			// 服务端的返回值对象
//			if (dfs != null && dfs.isSuccess())
//			{
//				Vector<Vector> ret = (Vector<Vector>)dfs.getReturnValue();
//				System.out.println("=========size:" + ret.size());
//				if(ret.size() > 0)
//				{
//					Vector row = ret.get(0);
//					String current_token_count = (String)row.get(0);
//					System.out.println("=========count:" + current_token_count);
//					viewCurrentTokenCount.setText(current_token_count);
//				}
//				// 没有积分
//				else
//					viewCurrentTokenCount.setText("0");
//			}
//		}

		/* (non-Javadoc)
		 * @see com.eva.android.widget.DataLoadingAsyncTask#onPostExecuteImpl(java.lang.Object)
		 */
		@Override
		protected void onPostExecuteImpl(Object result)
		{
			Vector<Vector> ret = (Vector<Vector>)result;
			System.out.println("=========size:" + ret.size());
			if(ret.size() > 0)
			{
				Vector row = ret.get(0);
				String current_token_count = (String)row.get(0);
				System.out.println("=========count:" + current_token_count);
				viewCurrentTokenCount.setText(current_token_count);
			}
			// 没有积分
			else
				viewCurrentTokenCount.setText("0");
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data)
	{
		if (resultCode == Activity.RESULT_OK)
		{
			WidgetUtils.showToast(RechargeActivity.this, $$(R.string.common_mall_recharge_score_pay_success), ToastType.INFO);
		}
		else
		{
			WidgetUtils.showToast(RechargeActivity.this, $$(R.string.common_mall_recharge_score_pay_failure), ToastType.INFO);
		}
		refreshCurrentTokenCountAsync();
	}

	@Override
	public void onDestroy()
	{
		stopService(new Intent(this, PayPalService.class));
		super.onDestroy();
	}
	
	@Override
	protected DataFromServer queryData(String... arg0)
	{
		// 要发送给服务端的对象
		return MallGlobal.getMallProviderInstance(this).getRobotimeMall().getAuthedService().sendObjToServer(
				DataFromClient.n().setProcessorId(CommonProcessorConst.PROCESSOR_SCORE)
						.setJobDispatchId(JobDispatchConst.SCORE_RECHARGE_ETC)
						.setActionId(SysActionConst.ACTION_APPEND3)
						.setNewData(MallGlobal.getMallProviderInstance(this).getRobotimeMall().getLoginedUserUid()));
	}

	/* (non-Javadoc)
	 * @see com.eva.android.widget.DataLoadableActivity#refreshToView(java.lang.Object)
	 */
	@Override
	protected void refreshToView(Object result)
	{
		ArrayList<TokenRechangeHistory> listData = (ArrayList<TokenRechangeHistory>) result;
		lvRechangeHistoryAdapter.setListData(listData);
		lvRechangeHistoryAdapter.notifyDataSetChanged();
	}
	
	@Override
	public void finish()
	{
		this.setResult(Activity.RESULT_OK);
		super.finish();
	}
	
	
	/**
	 * 默认的返回按钮实现回调.
	 */
	public void onBackPressed()
	{
		setResult(Activity.RESULT_OK);
		super.onBackPressed();
	}
}
